<template>
  <a-modal
    title="操作"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading" v-if="setHow">
      <a-form :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="已选分账账户"
        >
          <a-table :pagination="false"  :dataSource="dataSource" :columns="columns" style="font-size: 60px">
            <template slot="name" slot-scope="text, record">
              <editable-cell :text="text" />
            </template>
            <template slot="operation" slot-scope="text, record">
              <a-popconfirm
                v-if="dataSource.length"
                title="确认删除?"
                @confirm="() => onDelete(record.id)">
                <a href="javascript:;">X</a>
              </a-popconfirm>
            </template>
          </a-table>
        </a-form-item>

        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="添加分账账户">
          <a-select allowClear
            v-decorator="[ 'receiverId', {rules: [{ required: false, message: '添加分账账户' }],initialValue: defaultCompany}]"
            placeholder="请选择分账账户">
            <a-select-option :value="company.id" v-for="company in companyList" :key="company.id">
              {{company.name}}
            </a-select-option>
          </a-select>
        </a-form-item>
       <a-form-item label="商户总抽成金额" class="atFormItem" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-input  placeholder="商户总抽成金额（元）" ref="drawTotalFee"
                 v-decorator="[ 'drawTotalFee', {rules: [{ required: true, message: '请输入抽取商户总金额' }] }]"/>
        </a-form-item>
        <a-form-item class="atFormItem" label="最低订单金额抽成"  :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-input  placeholder="订单金额最低多少开始抽成（元）" ref="minimumDraw"
                   v-decorator="[ 'minimumDraw', {rules: [{ required: true, message: '请输入最低订单金额抽成' },{validator:this.checkContent.bind(this)}] }]"/>
        </a-form-item>
        <a-form-item class="atFormItem" label="每笔抽多少"  :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-input  placeholder="每个账户每笔抽多少钱（元）"
                 v-decorator="[ 'perDraw', {rules: [{ required: true, message: '请输入每笔抽多少' },{validator:this.CheckPerDraw.bind(this)}] }]"/>
        </a-form-item>
      </a-form>
    </a-spin>

<!--    二维码-->
      <img  v-if="!setHow" :src="'https://open.weixin.qq.com/qr/code?username='+subAppAccount"  />

  </a-modal>
</template>

<script>
  import { selectReceiverById ,serviceAll,addMerchantReceiver,delMerchantReceiver} from '@/api/merchantService/merchant'
  import pick from 'lodash.pick'
  export default {
    //--############  data() ###############-->
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        visible: false,
        confirmLoading: false,
        mdl: {},
        form: this.$form.createForm(this),
        isDisabled: false,
        defaultCompany:'',
        companyList:[],
        merchantId:'',
        subAppAccount:'',
        width:800,
        setHow:'',
        dataSource: [
          {
          id: '0',
          name: 'Edward King 0',
          account:'45'

        }, {
          id: '1',
          name: 'Edward King 1',
          account: '32',

        }],
        columns: [
          {
          title: '名称',
          dataIndex: 'name',
          width: '30%',
          // scopedSlots: { customRender: 'name' },
        }, {
          title: '账号',
          dataIndex: 'account',
          width:'50%'
        }, {
          title: '删除',
          dataIndex: 'operation',
          width:'15%',
          scopedSlots: { customRender: 'operation' },
        }],

      }

    },
    //--############  data() ###############-->

    created() {
      serviceAll().then(res => { //下拉列表
        this.companyList = res.result
      })
    },
    //--############  methods() ###############-->
    methods: {
      onDelete (id) {//删除
        let parameter = {
          merchantId: this.merchantId,
          receiverId:id
        }
        // delMerchantReceiver(parameter).then(res=>{
        //   const dataSource = [...this.dataSource]
        //   this.dataSource = dataSource.filter(item => item.id !== id)
        // })
      },
      checkContent(rule, value, callback) {
        let drawTotalFee = Number(this.$refs.drawTotalFee.value)
        let setValue = Number(value)
        if (setValue > drawTotalFee) {
          callback('最低金额不能大于总抽成金额！')
          return
        }
        callback()
      },
      CheckPerDraw(rule, value, callback) {
        let minimumDraw = Number(this.$refs.minimumDraw.value * 0.3)
        let setValue = Number(value)
        if (setValue > minimumDraw) {
          callback('不能大于最低金额的30%！')
          return
        }
        callback()
      },

      receiver(record,e) { //分账展示
        this.mdl = Object.assign({}, record)
        if(e =='device'){ //二维码
          if(!record.subAppAccount){
            this.$message.error('原始ID不能为空！')
            return
          }
          this.subAppAccount = record.subAppAccount
          this.setHow = false
          this.width = 500
        }
        else {
          selectReceiverById(record.id).then(res=>{
            console.log('表格',res)
            let obj = res.result
            this.dataSource = obj
          })
          this.setHow = true
          this.width = 800
          this.mdl.drawTotalFee = record.drawTotalFee / 100
          this.mdl.minimumDraw = record.minimumDraw / 100
          this.mdl.perDraw = record.perDraw / 100
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.mdl, 'drawTotalFee','minimumDraw', 'perDraw'))
          })
        }

        this.isDisabled = false
        this.visible = true
        this.merchantId =record.id
      },

      close() {
        this.$emit('close')
        this.visible = false
        this.form.resetFields()
        this.mdl={}

      },
      handleOk() {
        const _this = this
        if(!this.setHow){
          _this.$emit('ok')
          _this.close()
          return
        }
        // 触发表单验证
        this.form.validateFields((err, values) => {
          // 验证表单没错误
          if (!err) {
            _this.confirmLoading = true
            values.merchantId = _this.merchantId
            values.drawTotalFee = values.drawTotalFee == null || values.drawTotalFee == undefined || values.drawTotalFee == NaN ? null : values.drawTotalFee * 100
            values.minimumDraw = values.minimumDraw == null || values.minimumDraw == undefined || values.minimumDraw == NaN ? null : values.minimumDraw * 100
            values.perDraw = values.perDraw == null || values.perDraw == undefined || values.perDraw == NaN ? null : values.perDraw * 100
            addMerchantReceiver(values).then((res) => {
              if (res.code === 200) {
                _this.$message.success('保存成功')
                _this.$emit('ok')
                _this.close()
              }else {
                this.$notification.error({
                  message: '错误',
                  description: res.message,
                  duration: 4
                })
              }
            }).catch(() => {
              // Do something
            }).finally(() => {
              _this.confirmLoading = false
            })
          }
        })
      },
      handleCancel() {
        this.close()
      },
    }
    //--############  methods() ###############-->
  }
</script>

<style scoped>
  .editable-cell {
    position: relative;
  }

  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    line-height: 18px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell:hover .editable-cell-icon {
    display: inline-block;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
</style>
